package controller

import (
	"fmt"
	"github.com/kataras/iris"
	"github.com/kataras/iris/mvc"
	"imooc.com/demo_pms/models"
	"imooc.com/demo_pms/services"
)

type PayrollController struct {
	Ctx        iris.Context
	PayService services.PayrollService
}

func (p *PayrollController) PostCreate() mvc.Result {
	wageData := models.Payroll{}
	err := p.Ctx.ReadForm(&wageData)
	if err != nil {
		return mvc.View{
			Name: "postWage.html",
			Err:  err,
		}
	}
	dataList := []models.Payroll{}
	dataList = append(dataList, wageData)
	// 将转化后数据插入db
	i, err := p.PayService.Create(dataList)
	if err != nil {
		return mvc.View{
			Name: "postWage.html",
			Err:  err,
		}
	}
	return mvc.Response{
		Text: fmt.Sprintf("成功导入%d条数据", i),
	}
}

func (p *PayrollController) PutUpdate() mvc.Result {
	wageData := models.Payroll{}
	err := p.Ctx.ReadForm(&wageData)
	if err != nil {
		return mvc.View{
			Name: "postWage.html",
			Err:  err,
		}
	}
	err = p.PayService.Update(&wageData, []string{"wages"})
	if err != nil {
		return mvc.View{
			Name: "postWage.html",
			Err:  err,
		}
	}
	return mvc.View{
		Name: "postWage.html",
	}
}
